<?php

namespace App\Common\ElasticSearch;

use App\Common\Utill\ElasticSearch;

/**
 * Class EsLog
 * 日志记录
 *
 * @package App\Common\ElasticSearch
 *
 */
class EsLog
{
    /**
     * 创建视频日志索引
     *
     * @param string $indexName
     *
     * @return array
     * @throws \Exception
     *
     */
    public static function video_index(string $indexName, int $shards = 1, int $replicas = 1, bool $isSql = false)
    {
        $mappings = [
            "user_id" => ["type" => "long"],
            "video_id" => ["type" => "long"],
            "error_type" => ["type" => "keyword"],
            "source" => ["type" => "keyword"],
            "timeStamp" => ["type" => "long"],
            "timeDate" => [
                "type" => "date",
                "format" => "yyyy-MM-dd HH:mm:ss",
                "fields" => [
                    "keyword" => [
                        "type" => "keyword"
                    ]
                ]
            ]
        ];
        $settings = [];
        $res = (ElasticSearch::instance())->settings($settings, $shards, $replicas)
            ->mappings($mappings)
            ->isSql($isSql)
            ->createIndex($indexName);
        if (!empty($res['acknowledged']) && !empty($res['index'])) {
            $resData['code'] = 200;
            $resData['msg'] = $res['index'] . "创建成功";
            return $resData;
        }
        $resData['code'] = $res['status'] ?? 500;
        $resData['msg'] = $indexName . "创建失败。原因：" . $res['error']['reason'] ?? "";
        return $resData;
    }

    /**
     * 视频日志写入
     * @param $params
     *
     * @return bool
     * @throws \Exception
     *
     */
    public static function video($params)
    {
        $info = [
            "user_id" => (int)$params['user_id'] ?? 0,
            "video_id" => (int)$params['videoId'] ?? 0,
            "error_type" => (int)$params['error_type'] ?? 0,
            "source" => (string)$params['source'] ?? "",
            "timeStamp" => time(),
            "timeDate" => date("Y-m-d H:i:s"),
        ];
        $es = ElasticSearch::instance();
        return $es->index("log_video")->data($info)->saveOne();

    }
}
